import { avatarUri } from '@/constants/Uri'
import dayjs from 'dayjs'
import React, { useRef, useEffect, useState } from 'react'
import {
  StyleSheet,
  View,
  requireNativeComponent,
  ViewProps,
  findNodeHandle,
  UIManager
} from 'react-native'

type NativeInfoViewType =
  | ViewProps
  | {
      // 这部分是自定义的属性
      avatar: string
      name: string
      desc: string
      onShapeChange: (e: any) => void
    }
const originViewName = 'nativeInfoView' // 名字来源于原生java
const NativeInfoView =
  requireNativeComponent<NativeInfoViewType>(originViewName)

export default () => {
  const ref = useRef(null)
  const timeRef = useRef<Number>(null)
  const [desc, setdesc] = useState('其它几个都是在原生注册了的props？？？')
  const [nowTime, setnowTime] = useState('')
  useEffect(() => {
    timeRef!.current = setInterval(() => {
      // sendCommand('setShape', ['round']);
      console.log(NativeInfoView, '=====')
      setdesc(Math.random().toFixed(3) + 'style是从ViewProps中继承过来的')
    }, 2000)

    setTimeout(() => {
      timeRef.current && clearInterval(timeRef.current)
    }, 12000)
  }, [])

  // 可以实时变动原生的DOM
  useEffect(() => {
    const timer = setInterval(() => {
      setnowTime(dayjs().format('YYYY MM/DD HH:mm:ss'))
    }, 1000)

    return () => {
      timer && clearInterval(timer)
    }
  }, [])


  // js调用api发送命令，调用原生组件的方法并传参
  const sendCommand = (command: string, params: any[]) => {
    const viewId = findNodeHandle(ref.current) // 记得给它搞ref，不然找不到这个id
    // @ts-ignore
    const commands = UIManager[originViewName].Commands[command].toString()
    UIManager.dispatchViewManagerCommand(viewId, commands, params)
  }

  useEffect(() => {
    setTimeout(() => {
      sendCommand('setShape', ['round'])
      console.log('setShape send.....')
    }, 4000)
    return () => {}
  }, [])

  // style是从ViewProps中继承过来的 ,而其它几个都是在原生注册了的props
  return (
    <NativeInfoView
      ref={ref}
      style={styles.infoView}
      avatar={avatarUri}
      name={'liuyisong '}
      desc={desc + nowTime}
      onShapeChange={(e: any) => {
        console.log(e.nativeEvent.shape)
      }}
    />
  )
}

const styles = StyleSheet.create({
  infoView: {
    width: '100%',
    height: 120,
    backgroundColor: 'pink'
  },
})
